<template>
  <el-button type="primary" @click="showAddAddressDialog">新增地址</el-button>
  <el-button type="primary" @click="navigateToHealthInfo">查看健康档案</el-button>
  <el-button type="primary" @click="quit">退出登录</el-button>
  <el-descriptions title="用户信息" border>

    <el-descriptions-item label="头像">
      <el-image
          style="width: 100px; height: 100px"
          :src="attachImg(userinfo.headpic)"
          @click="navigateToHealthInfo"
      />

    </el-descriptions-item>
    <el-descriptions-item label="昵称">{{ userinfo.nickname }}</el-descriptions-item>
    <el-descriptions-item label="用户名">{{ userinfo.username }}</el-descriptions-item>
    <el-descriptions-item label="电话">{{ userinfo.userphone }}</el-descriptions-item>
    <el-descriptions-item label="地址">{{ userinfo.address }}</el-descriptions-item>
  </el-descriptions>

  <el-table :data="addressInfo" style="width: 100%">
    <el-table-column prop="consignee" label="收货人"></el-table-column>
    <el-table-column prop="consigneephone" label="联系电话"></el-table-column>
    <el-table-column prop="useraddress" label="详细地址"></el-table-column>
    <el-table-column label="操作" width="180">
      <template #default="scope">
        <el-button type="text" size="small" @click="editInfo(scope.row)">修改</el-button>
        <el-button type="text" size="small" @click="deleteInfo(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog title="修改地址信息" v-model="dialogVisible" width="30%">
    <el-form :model="currentAddress">
      <el-form-item label="收货人" :label-width="formLabelWidth">
        <el-input v-model="currentAddress.consignee"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" :label-width="formLabelWidth">
        <el-input v-model="currentAddress.consigneephone"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" :label-width="formLabelWidth">
        <el-input v-model="currentAddress.useraddress"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updateAddress">确定</el-button>
    </template>
  </el-dialog>



  <el-dialog title="新增地址信息" v-model="addAddressDialogVisible" width="30%">
    <el-form :model="newAddress">
      <el-form-item label="收货人" :label-width="formLabelWidth">
        <el-input v-model="newAddress.consignee"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" :label-width="formLabelWidth">
        <el-input v-model="newAddress.consigneephone"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" :label-width="formLabelWidth">
        <el-input v-model="newAddress.useraddress"></el-input>
      </el-form-item>
      <el-button type="primary" @click="selectAddress">选择地址</el-button>
      <el-dialog title="选择地址" v-model="mapDialogVisible" width="50%">
        <div id="mapContainer" style="width: 100%; height: 400px;"></div>
      </el-dialog>
    </el-form>
    <template #footer>
      <el-button @click="addAddressDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addAddress">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElDescriptions, ElDescriptionsItem, ElImage, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElTable, ElTableColumn } from 'element-plus';
import {attachImg} from "@/api";

export default {
  components: {
    ElDescriptions,
    ElDescriptionsItem,
    ElImage,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElTable,
    ElTableColumn
  },
  data() {
    return {
      userinfo: {},
      addressInfo: [],
      userId: null,
      dialogVisible: false,
      currentAddress: {},
      formLabelWidth: '120px',
      newAddress: {}, // 新增地址的表单数据
      addAddressDialogVisible: false, // 控制新增地址弹出框的显示
      mapDialogVisible: false,
      map: null,
      mouseTool: null,
    };
  },
  methods: {
    attachImg,
    selectAddress() {
      this.mapDialogVisible = true;
      this.initMap();
    },
    quit(){
      const token = localStorage.getItem('sessionToken');
      axios.get(`http://localhost:9099/user/quit?token=${token}`).then(res=>{
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
            duration: 2000
          });
          localStorage.removeItem('sessionToken');
          localStorage.removeItem('userId');
          this.$router.push('/loginView');
        } else {
          ElMessage({
            message: res.data.msg,
            type: 'error',
            duration: 2000
          });
        }
      })
    },
    initMap() {
      if (!window.AMap) {
        console.error('AMap is not loaded');
        ElMessage.error('高德地图库未加载');
        return;
      }

      this.map = new window.AMap.Map('mapContainer', {
        resizeEnable: true,
        center: [116.397428, 39.90923], // 地图中心点
        zoom: 13, // 地图显示的缩放级别
        key: '你的API密钥' // 使用正确的API密钥
      });

      window._AMapSecurityConfig = {
        securityJsCode: '你的安全密钥', // 替换为您的安全密钥
      };

      window.AMap.plugin('AMap.Geocoder', () => {
        this.map.on('click', (event) => {
          this.getAddress(event.lnglat);
        });
      });
    },

// 方法：获取地址
    getAddress(lnglat) {
      if (!lnglat || !lnglat.lng || !lnglat.lat) {
        ElMessage.error('无效的经纬度参数');
        return;
      }

      const geocoder = new window.AMap.Geocoder({
        city: "全国", // 指定城市
      });
      geocoder.getAddress(lnglat, (status, result) => {
        console.log('逆地理编码结果：', status, result); // 调试日志
        if (status === 'complete' && result.info === 'OK') {
          this.newAddress.useraddress = result.regeocode.formattedAddress;
          ElMessage.success('地址选择成功');
          this.mapDialogVisible = false;
        } else {
          ElMessage.error(`地址获取失败：${result.info || '未知错误'}`);
        }
      });
    },

    async fetchUserInfo() {
      this.userId = localStorage.getItem('userId');
      if (this.userId) {
        try {
          const response = await axios.get(`hospital-user?id=${this.userId}`);
          if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
            this.userinfo = response.data.data[0];
          } else {
            ElMessage.error('没有找到数据');
          }
        } catch (error) {
          console.error('Error fetching user info:', error);
          ElMessage.error('获取用户信息失败');
        }
      } else {
        ElMessage.error('用户ID未找到');
      }
    },
    async fetchAddressInfo() {
      if (this.userId) {
        try {
          const response = await axios.get(`hospital-address?id=${this.userId}`);
          if (response.data.code === 200 && response.data.data) {
            this.addressInfo = response.data.data;
          } else {
            ElMessage.error('没有找到地址数据');
          }
        } catch (error) {
          console.error('Error fetching address info:', error);
          ElMessage.error('获取地址信息失败');
        }
      } else {
        ElMessage.error('用户ID未找到');
      }
    },
    navigateToHealthInfo() {
      if (this.userinfo.id) {
        this.$router.push({name: 'healthinfo', params: {userId: this.userinfo.id}});
      } else {
        ElMessage.error('用户ID未找到');
      }
    },
    editInfo(row) {
      this.currentAddress = {...row};
      this.dialogVisible = true;
    },
    deleteInfo(row) {
      const addressId = row.id;
      this.$confirm('此操作将永久删除该地址, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`hospital-address-delete/${addressId}`)
            .then(response => {
              if (response.status === 200) {
                ElMessage.success(response.data.message || '地址删除成功');
                this.fetchAddressInfo();
              } else {
                ElMessage.error('删除地址失败');
                this.fetchAddressInfo();
              }
            })
            .catch(error => {
              console.error('Error deleting address:', error);
              if (error.response) {
                ElMessage.error(error.response.data.message || '删除地址时发生错误');
              } else {
                ElMessage.error('删除地址时发生未知错误');
              }
            });
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },
    updateAddress() {
      if (this.currentAddress.consigneephone.length !== 11) {
        ElMessage.error('电话号码不为11位，请重新输入。');
        return;
      }

      const updatedAddress = this.currentAddress;
      const addressId=this.currentAddress.id
      axios.put(`hospital-address-update/${addressId}`, updatedAddress)
          .then(response => {
            if (response.status === 200) {
              ElMessage.success(response.data.message || '修改成功');
              this.fetchAddressInfo();
            } else {
              this.fetchAddressInfo();
            }
            this.dialogVisible = false;
          })
          .catch(error => {
            console.error('Error updating address:', error);
            ElMessage.error('发生错误');
            this.dialogVisible = false;
          });
    },
    showAddAddressDialog() {
      this.newAddress = {};
      this.addAddressDialogVisible = true;
    },
    addAddress() {
      if (this.newAddress.consigneephone.length !== 11) {
        ElMessage.error('电话号码不为11位，请重新输入。');
        return;
      }
      const userIdFromStorage = localStorage.getItem('userId');
      this.userId = userIdFromStorage;
      this.newAddress.userid = this.userId;  axios.post('hospital-address-add', this.newAddress)
          .then(response => {
            if (response.data.success) {
              ElMessage.success(response.data.message || '地址添加成功');
              this.fetchAddressInfo();
              this.addAddressDialogVisible = false;
            } else {

              this.fetchAddressInfo();
              this.addAddressDialogVisible = false;
            }
          })
          .catch(error => {
            console.error('Error adding address:', error);
            ElMessage.error('添加地址时发生错误');
          });
    }},
  mounted() {
    this.fetchUserInfo();
    this.fetchAddressInfo();
  }
};
</script>

<style> /* Your styles */ </style>